package shop.controller.front.user;

import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import shop.core.FrontBaseController;
import shop.core.Services;
import shop.core.common.bean.JSONResult;
import shop.core.common.dao.page.PagerModel;
import shop.core.plugins.sms.SMS;
import shop.core.plugins.sms.SMSSendCodeResult;
import shop.core.plugins.sms.SMSVerifyCodeResult;
import shop.core.plugins.wxlogin.AccessToken;
import shop.core.plugins.wxlogin.WxUrlType;
import shop.core.plugins.wxlogin.WxUtil;
import shop.core.plugins.wxmsg.WxMsgUtil;
import shop.core.plugins.wxpay.WXPayConstants;
import shop.core.plugins.wxpay.WXPayUtil;
import shop.core.util.AddressUtils;
import shop.core.util.QRcodeUtils;
import shop.core.util.StrUtils;
import shop.services.front.order.OrderService;
import shop.services.front.order.bean.Order;
import shop.services.front.voucher.VoucherService;
import shop.services.front.voucher.bean.Voucher;
import shop.services.manage.system.bean.User;
import shop.services.manage.system.impl.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by wzl on 2017/9/21.
 */
@Controller
@RequestMapping("/front/user/")
public class UserController extends FrontBaseController<User> {
    private final  static  String USER_ROLE_MANAGE_ADMIN="1";
    private final  static  String USER_ROLE_FRONT_PARTNER="2";
    private final  static  String USER_ROLE_FRONT_MEMBER="3";
    private final  static  String USER_ROLE_FRONT_COMMON="4";
    @Resource
    private UserService userService;
    @Resource
    private OrderService orderService;
    @Resource
    private VoucherService voucherService;
    @Override
    public Services<User> getService() {
        return userService;
    }


    /**
     * 跳转到微信首页
     *
     * @return
     */
    @RequestMapping("toIndex")
    public String toIndex() {
        return "/front/index";
    }

    /**
     * 跳转到个人中心
     *
     * @return
     */
    @RequestMapping("toMyPage")
    public String toMyPage() {
        return "/front/userCenter/userCenter";
    }

    /**
     * 跳转到个人信息页面
     *
     * @return
     */
    @RequestMapping("toPersonal")
    public String toPersonal() {
        return "/front/userCenter/userInf";
    }


    /**
     * 跳转到入股店铺页面
     *
     * @return
     */
    @RequestMapping("toStoreList")
    public String toStoreList() {
        return "/front/userCenter/storeList";
    }

    /**
     * 跳转到我的团队页面
     *
     * @return
     */
    @RequestMapping("toMyTeam")
    public String toMyTeam() {
        return "/front/userCenter/myTeam";
    }

    /**
     * 跳转到我的团队订单页面
     *
     * @return
     */
    @RequestMapping("toSubOrder")
    public String toSubOrder() {
        return "/front/userCenter/vipOrder";
    }

    /**
     * 跳转到余额明细页面
     *
     * @return
     */
    @RequestMapping("toBalanceList")
    public String toBalanceList() {
        return "/front/wallet/recordList";
    }

    /**
     * 跳转到绑定手机页面
     *
     * @return
     */
    @RequestMapping("toBindPhone")
    public String toBindPhone() {
        return "/front/userCenter/bindPhone";
    }


    /**
     * 微信授权登陆
     *
     * @return
     */
    @RequestMapping(value = "toWx", method = RequestMethod.GET)
    public String toWx(HttpServletRequest request) {
        String pid = request.getParameter("pid");
        String id = request.getParameter("id");
        String cashVoucherID = request.getParameter("cashVoucherID");
        String type = request.getParameter("type");
        String seatID = request.getParameter("seatID");
        String menuID = request.getParameter("menuID");
        String productTZ = request.getParameter("productTZ");
        String userCenterTZ = request.getParameter("userCenterTZ");
        String myTeamTZ = request.getParameter("myTeamTZ");
        String recordListTZ = request.getParameter("recordListTZ");
        String orderID = request.getParameter("orderID");
        String activityID = request.getParameter("activityID");
        String partnerApplyID = request.getParameter("partnerApplyID");
        String appidUrl = "?appid=" + systemManager.getSystemSetting().getAppid().trim() + "&";
        String redirect_uri = "redirect_uri=" + systemManager.getSystemSetting().getWww() + "/rest/front/user/callBack";
        String typeUrl = "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        if (!StringUtils.isBlank(pid)) {
            redirect_uri = redirect_uri + "?pid=" + pid;
        }else if(!StringUtils.isBlank(id)) {
            redirect_uri = redirect_uri + "?id=" + id;
        }else if(!StringUtils.isBlank(cashVoucherID)) {
            redirect_uri = redirect_uri + "?cashVoucherID=" + cashVoucherID;
        } else if(!StringUtils.isBlank(type)) {
            redirect_uri = redirect_uri + "?type=" + type;
        } else if(!StringUtils.isBlank(seatID)){
            redirect_uri = redirect_uri + "?seatID=" + seatID;
        }else if(!StringUtils.isBlank(menuID)){
            redirect_uri = redirect_uri + "?menuID=" + menuID;
        } else if(!StringUtils.isBlank(productTZ)){
            redirect_uri = redirect_uri + "?productTZ=" + productTZ;
        }else if(!StringUtils.isBlank(userCenterTZ)){
            redirect_uri = redirect_uri + "?userCenterTZ=" + userCenterTZ;
        }else if(!StringUtils.isBlank(myTeamTZ)){
            redirect_uri = redirect_uri + "?myTeamTZ=" + myTeamTZ;
        } else if(!StringUtils.isBlank(recordListTZ)){
            redirect_uri = redirect_uri + "?recordListTZ=" + recordListTZ;
        } else if(!StringUtils.isBlank(orderID)){
            redirect_uri = redirect_uri + "?orderID=" + orderID;
        } else if(!StringUtils.isBlank(activityID)){
            redirect_uri = redirect_uri + "?activityID=" + activityID;
        } else if(!StringUtils.isBlank(partnerApplyID)){
            redirect_uri = redirect_uri + "?partnerApplyID=" + partnerApplyID;
        } else{
        }
        logger.debug("redirect_uri路径"+redirect_uri);
        return "redirect:" + WxUrlType.authorizeUrl + appidUrl + redirect_uri + typeUrl;
    }

    /**
     * 微信回调方法
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "callBack", method = RequestMethod.GET)
    public String callBack(HttpSession session, HttpServletRequest request) {
        String pid = request.getParameter("pid");
        String id = request.getParameter("id");
        String cashVoucherID = request.getParameter("cashVoucherID");
        String type = request.getParameter("type");
        if(!StringUtils.isBlank(id)){
            String []ids=id.split("_");
            if(StringUtils.isBlank(pid)){
                logger.debug("ids[1]:"+ids[1]);
                pid=ids[1];
                logger.debug("pid=ids[1]: "+pid);
            }
        }
        if(!StringUtils.isBlank(cashVoucherID)){
            String []ids=cashVoucherID.split("_");
            if(StringUtils.isBlank(pid)){
                pid=ids[1];
            }
        }
        String seatID = request.getParameter("seatID");
        String menuID = request.getParameter("menuID");
        String productTZ = request.getParameter("productTZ");
        String userCenterTZ = request.getParameter("userCenterTZ");
        String myTeamTZ = request.getParameter("myTeamTZ");
        String recordListTZ = request.getParameter("recordListTZ");
        String orderID = request.getParameter("orderID");
        String activityID = request.getParameter("activityID");
        String partnerApplyID = request.getParameter("partnerApplyID");
        String code = request.getParameter("code");
        Map<String, String> params = new HashMap<>();
        params.put("appid", systemManager.getSystemSetting().getAppid());
        params.put("secret", systemManager.getSystemSetting().getSecret());
        params.put("code", code);
        params.put("grant_type", "authorization_code");
        AccessToken accessToken = WxUtil.sendRequest(WxUrlType.accessTokenUrl, HttpMethod.GET, params, null, AccessToken.class);
        Map<String, String> getUserInfoParams = new HashMap<>();
        getUserInfoParams.put("access_token", accessToken.getAccess_token());
        getUserInfoParams.put("openid", accessToken.getOpenid());
        getUserInfoParams.put("lang", "zh_CN");
        Map<String, String> wxReturn = WxUtil.sendRequest(WxUrlType.userInfoUrl, HttpMethod.GET, getUserInfoParams, null, Map.class);
        logger.debug("微信登陆返回信息：" + wxReturn);
        String openID = accessToken.getOpenid();
        logger.debug("userOpenId：" + openID);
        session.setAttribute("userOpenId", openID);
        User user = userService.selectByOpenId(accessToken.getOpenid());
        if (user != null) {
            user.setNickname(wxReturn.get("nickname"));
            user.setSex(String.valueOf(wxReturn.get("sex")));
            user.setIcon(wxReturn.get("headimgurl"));
            if (!StringUtils.isBlank(pid)&&!"2".equals(user.getRid())&&"0".equals(user.getPid())) {
                user.setPid(pid);
                user.setRid(USER_ROLE_FRONT_MEMBER);
                userService.update(user);
                //会员加入模板消息通知
                User supUser=new User();
                supUser.setId(pid);
                supUser=userService.selectOne(supUser);
                Map<String, String> msgParam = new HashMap<>();
                msgParam.put("first", "尊敬的股东，您有新的会员加入！");
                msgParam.put("keyword1", user.getNickname());
                msgParam.put("keyword2", user.getPhone());
                msgParam.put("keyword3", user.getId());
                msgParam.put("remark", "点击查看详情");
                WxMsgUtil.sendMemberJoinMsg(msgParam, systemManager, supUser.getOpenID());
            }else if(!StringUtils.isBlank(seatID)){
                String []seatIDs=seatID.split("_");
                user.setSeatID(seatIDs[0]);
                userService.update(user);
            }else{
                userService.update(user);
            }
            session.setAttribute("userInfo", user);
        } else {
            User loginUser = new User();
            loginUser.setOpenID(wxReturn.get("openid"));
            loginUser.setNickname(wxReturn.get("nickname"));
            loginUser.setSex(String.valueOf(wxReturn.get("sex")));
            loginUser.setIcon(wxReturn.get("headimgurl"));
            String username = StrUtils.getUUID();
            String password = StrUtils.getUUID();
            loginUser.setUsername(username);
            loginUser.setPassword(password);
            loginUser.setRid(USER_ROLE_FRONT_COMMON);
            if (!StringUtils.isBlank(pid)) {
                loginUser.setPid(pid);
                loginUser.setRid(USER_ROLE_FRONT_MEMBER);
                userService.insert(loginUser);
                //会员加入模板消息通知
                loginUser=userService.selectOne(loginUser);
                User supUser=new User();
                supUser.setId(pid);
                supUser=userService.selectOne(supUser);
                Map<String, String> msgParam = new HashMap<>();
                msgParam.put("first", "尊敬的股东，您有新的会员加入！");
                msgParam.put("keyword1", loginUser.getNickname());
                msgParam.put("keyword2", loginUser.getPhone());
                msgParam.put("keyword3", loginUser.getId());
                msgParam.put("remark", "点击查看详情");
                WxMsgUtil.sendMemberJoinMsg(msgParam, systemManager, supUser.getOpenID());
            }else if(!StringUtils.isBlank(seatID)){
                String []seatIDs=seatID.split("_");
                loginUser.setSeatID(seatIDs[0]);
                userService.insert(loginUser);
            }else{
                userService.insert(loginUser);
            }
            QRcodeUtils qrCodeUtils = new QRcodeUtils();
            String iconUrl = qrCodeUtils.getIconByUrl(request, loginUser.getIcon());
            String contents = systemManager.getSystemSetting().getWww() + "/rest/front/user/toWx?pid=" + loginUser.getId();
            loginUser.setQrCode(qrCodeUtils.createLogoQrcode(request, contents, iconUrl));
            userService.update(loginUser);
            session.setAttribute("userInfo", loginUser);
        }
        if(!StringUtils.isBlank(id)){
            String []ids=id.split("_");
            return "redirect:/rest/front/voucher/toGetVoucher?id="+ids[0];
        }else if(!StringUtils.isBlank(cashVoucherID)){
            String []ids=cashVoucherID.split("_");
            return "redirect:/rest/front/order/toGetCashVoucher?cashVoucherID="+ids[0];
        } else if(!StringUtils.isBlank(type)){
            return "redirect:/rest/front/voucher/toSetVoucher?type="+type;
        } else if(!StringUtils.isBlank(productTZ)){
            return "redirect:/rest/front/product/toStoreList";
        } else if(!StringUtils.isBlank(userCenterTZ)){
            return "redirect:/rest/front/user/toMyPage";
        }else if(!StringUtils.isBlank(myTeamTZ)){
            return "redirect:/rest/front/user/toMyTeam";
        }else if(!StringUtils.isBlank(recordListTZ)){
            return "redirect:/rest/front/record/toRecordList";
        } else if(!StringUtils.isBlank(orderID)){
            return "redirect:/rest/front/order/toOrderDetail?orderID="+orderID;
        }else if(!StringUtils.isBlank(activityID)){
            return "redirect:/rest/front/activity/toActivityDetail?activityID="+activityID;
        }else if(!StringUtils.isBlank(partnerApplyID)){
            return "redirect:/rest/front/partnerapply/toPartnerApply";
        } else if(!StringUtils.isBlank(seatID)){
            String []seatIDs=seatID.split("_");
            return "redirect:/rest/front/product/toProductList?storeID="+seatIDs[1]+"&type=in";
        }  else if(!StringUtils.isBlank(menuID)){
            return "redirect:/rest/front/product/toProductList?storeID="+menuID+"&type=in";
        } else{
            return "redirect:/rest/front/user/toIndex";
        }
    }

    /**
     * 微信扫一扫
     *
     * @return
     */
    @RequestMapping("toScan")
    @ResponseBody
    public JSONResult wxScan(String pageUrl) {
        jsonResult = new JSONResult();
        //随机生成签名的时间戳
        String timeStamp = String.valueOf(new Date().getTime() / 1000);
        //随机生成签名，使用UUID来获取唯一签名
        String nonceStr = UUID.randomUUID().toString().replace("-", "");
        Map resMap = new HashMap<>();
        try {
            Map<String, String> reqData = new HashMap<String, String>();
            reqData.put("jsapi_ticket", systemManager.getJsapiTicket());
            reqData.put("timestamp", timeStamp);
            reqData.put("noncestr", nonceStr);
            //微信上传图片所对应的接口，使用全部路径
            reqData.put("url", pageUrl);
            String signature = WXPayUtil.generateSignature(reqData, null, WXPayConstants.SignType.SHA1);
            resMap.put("appId", systemManager.getSystemSetting().getAppid());
            resMap.put("timestamp", timeStamp);
            resMap.put("noncestr", nonceStr);
            resMap.put("signature", signature);
            logger.info("获取微信参数:" + resMap);
        } catch (Exception e) {
            logger.error("获取微信jsapi参数失败:" + e.toString());
            jsonResult.setSuccess(false);
            jsonResult.setMessage("获取微信jsapi参数失败");
            return jsonResult;
        }
        jsonResult.setSuccess(true);
        jsonResult.setData(resMap);
        return jsonResult;
    }

    /**
     * 获取缓存用户信息
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "getSession", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult getSession(HttpSession session) {
        JSONResult jsonResult = new JSONResult();
        Map result = new HashMap<>();
        if (session.getAttribute("userInfo") != null) {
            result.put("user", session.getAttribute("userInfo"));
        } else {
            result.put("user", null);
        }
        jsonResult.setData(result);
        jsonResult.setSuccess(true);
        return jsonResult;
    }

    /**
     * 更新缓存用户信息
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "updateSession", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult updateSession(HttpSession session) {
        JSONResult jsonResult = new JSONResult();
        Map result = new HashMap<>();
        if (session.getAttribute("userInfo") != null) {
            User user = (User) session.getAttribute("userInfo");
            user = userService.selectById(user.getId());
            session.setAttribute("userInfo", user);
            result.put("user", session.getAttribute("userInfo"));
        } else {
            result.put("user", null);
        }
        jsonResult.setData(result);
        jsonResult.setSuccess(true);
        return jsonResult;
    }

    /**
     * 查询登录用户
     *
     * @param
     * @return
     */
    @RequestMapping(value = "selectUser", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectUser(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("userInfo");
        jsonResult = new JSONResult();
        jsonResult.setData(user);
        return jsonResult;
    }

    /**
     * 更新用户信息
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "updateUser", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult updateUser(HttpServletRequest request, HttpSession session, User user) throws Exception {
        User loginUser = (User) request.getSession().getAttribute("userInfo");
        user.setId(loginUser.getId());
        jsonResult = new JSONResult();
        userService.update(user);
        User userInfo = userService.selectOne(user);
        session.setAttribute("userInfo", userInfo);//更新缓存
        return jsonResult;
    }

    /**
     * 发送验证码（绑定手机）
     *
     * @throws Exception
     */
    @RequestMapping(value = "getSMSCode", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult getSMSCode(HttpServletRequest request) throws Exception {
        JSONResult rs = new JSONResult();
        String mobile = request.getParameter("mobile");
        //根据手机号码查询用户信息，判断是否存在手机号码
        User user = new User();
        user.setPhone(mobile);
        List<User> userList = userService.selectList(user);

        if (userList.size() > 0) {
            rs.setSuccess(false);
            rs.setMessage("该手机已绑定其它账号，请重新填写手机号码！");
            return rs;
        }
        //发送短信
        SMS sms = new SMS();
        SMSSendCodeResult smsSendCodeResult = sms.sendCode(mobile, systemManager.getSystemSetting().getSmsTemplateId(), "86", null, null);
        if (smsSendCodeResult.getCode() == 200) {
            rs.setSuccess(true);
            rs.setMessage("短信发送成功！");
            rs.setData(smsSendCodeResult);
            logger.debug("验证码返回信息" + rs);
            return rs;
        } else {
            rs.setSuccess(false);
            rs.setMessage("短信发送失败！");
            return rs;
        }
    }

    /**
     * 校验验证码
     *
     * @throws Exception
     */
    @RequestMapping(value = "checkCode", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult checkCode(HttpServletRequest request) throws Exception {
        JSONResult jsonResult = new JSONResult();
        User user = (User) request.getSession().getAttribute("userInfo");
        // SmsId 短信验证码唯一标识   SmsContent 短信验证码内容
        String smsId = request.getParameter("SmsId");
        String smsContent = request.getParameter("SmsContent");
        String phone = request.getParameter("phone");
        SMS sms = new SMS();
        SMSVerifyCodeResult rs = sms.verifyCode(smsId, smsContent);//验证码验证方法
        if (rs.getSuccess() == null || !rs.getSuccess()) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage("短信验证码错误！");
        } else {
            jsonResult.setSuccess(true);
            user.setPhone(phone);
            userService.update(user);
        }
        return jsonResult;
    }

    /**
     * 查询用户下级列表
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("selectSubList")
    @ResponseBody
    public JSONResult selectSubList(HttpServletRequest request) throws Exception {
        User user = (User) request.getSession().getAttribute("userInfo");
        User userInfo = new User();
        userInfo.setPid(user.getId());
        List<User> userList = userService.selectSubList(userInfo);
        //添加消費金額
        if (userList!=null&&userList.size() > 0) {
            for(User oneUser :userList){
                Order order =new Order();
                order.setUserID(oneUser.getId());
                BigDecimal costAmount=orderService.selectCostAmount(order);
                if(costAmount!=null){
                    oneUser.setCostAmount(costAmount);
                }else{
                    oneUser.setCostAmount(new BigDecimal("0"));
                }
            }
        }
        jsonResult = new JSONResult();
        jsonResult.setData(userList);
        return jsonResult;
    }

    /**
     * 生成打折卷
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "insertVoucher", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult insertVoucher(HttpServletRequest request,Voucher voucher) throws Exception {
        User user = (User) request.getSession().getAttribute("userInfo");
        JSONResult jsonResult = new JSONResult();
        int id=voucherService.insert(voucher);
        Voucher voucherInfo=new Voucher();
        voucherInfo.setId(String.valueOf(id));
        voucherInfo=voucherService.selectOne(voucherInfo);
        voucherInfo.setType("discount");
        voucherInfo.setCreateType("front");
        voucherInfo.setStatus("n");
        QRcodeUtils qrCodeUtils = new QRcodeUtils();
        String contents = systemManager.getSystemSetting().getWww()+"/rest/front/voucher/toGetVoucher?id="+voucherInfo.getId()+"_"+user.getId();
        voucherInfo.setQrCode(qrCodeUtils.createQrcode(request, contents));
        voucherService.update(voucherInfo);
        jsonResult.setData(voucherInfo);
        return jsonResult;
    }

    /**
     * 生成充值优惠卷
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "insertBalanceVoucher", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult insertBalanceVoucher(HttpServletRequest request,Voucher voucher) throws Exception {
        User user = (User) request.getSession().getAttribute("userInfo");
        JSONResult jsonResult = new JSONResult();
        int id=voucherService.insert(voucher);
        Voucher voucherInfo=new Voucher();
        voucherInfo.setId(String.valueOf(id));
        voucherInfo=voucherService.selectOne(voucherInfo);
        voucherInfo.setType("cash");
        voucherInfo.setCreateType("front");
        voucherInfo.setStatus("n");
        QRcodeUtils qrCodeUtils = new QRcodeUtils();
        String contents = systemManager.getSystemSetting().getWww()+"/rest/front/order/toGetCashVoucher?cashVoucherID="+voucherInfo.getId()+"_"+user.getId();
        voucherInfo.setQrCode(qrCodeUtils.createQrcode(request, contents));
        voucherService.update(voucherInfo);
        jsonResult.setData(voucherInfo);
        return jsonResult;
    }

    /**
     * 生成二维码背景图
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "createBackgroundQrCode", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult createBackgroundQrCode(HttpServletRequest request,String id,String background) throws Exception {
        logger.debug("二维码背景图: "+id+"_"+background);
        User user = (User) request.getSession().getAttribute("userInfo");
        QRcodeUtils qrCodeUtils = new QRcodeUtils();
        String iconUrl = qrCodeUtils.getIconByUrl(request, background);
        logger.debug("背景图url: "+iconUrl);
        String contents = systemManager.getSystemSetting().getWww()+"/rest/front/voucher/toGetVoucher?id="+id+"_"+user.getId();
        String backgroundQrCode = qrCodeUtils.createBackgroundQrCode(request,contents,iconUrl);
        logger.debug("生成二维码背景图: "+backgroundQrCode);
        JSONResult jsonResult = new JSONResult();
        jsonResult.setData(backgroundQrCode);
        return jsonResult;
    }

    /**
     * 生成充值二维码背景图
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "createCashBgQrCode", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult createCashBgQrCode(HttpServletRequest request,String id,String background) throws Exception {
        logger.debug("二维码背景图: "+id+"_"+background);
        User user = (User) request.getSession().getAttribute("userInfo");
        QRcodeUtils qrCodeUtils = new QRcodeUtils();
        String iconUrl = qrCodeUtils.getIconByUrl(request, background);
        logger.debug("背景图url: "+iconUrl);
        String contents = systemManager.getSystemSetting().getWww()+"/rest/front/order/toGetCashVoucher?cashVoucherID="+id+"_"+user.getId();
        String backgroundQrCode = qrCodeUtils.createBackgroundQrCode(request,contents,iconUrl);
        logger.debug("生成二维码背景图: "+backgroundQrCode);
        JSONResult jsonResult = new JSONResult();
        jsonResult.setData(backgroundQrCode);
        return jsonResult;
    }

    /**
     * 判断是否处于配送范围之内
     * @param lat1,lng1,lat2,lng2
     * @return
     */
    @RequestMapping("getDistance")
    @ResponseBody
    public JSONResult getDistance(double lat1, double lng1, double lat2, double lng2) {
        logger.debug("经纬度："+lat1+","+lng1+";"+lat2+","+lng2);
        double distance = AddressUtils.getDistance(lat1,lng1,lat2,lng2);
        logger.debug("距离："+distance);
//        double sendDistance=3000;
//        Boolean result=Double.doubleToLongBits(distance)<Double.doubleToLongBits(sendDistance);
        JSONResult jsonResult = new JSONResult();
        jsonResult.setData(distance);
        return jsonResult;
    }

    @Override
    public JSONResult deleteJson(HttpServletRequest request, User user) throws Exception {
        return null;
    }
}
